/*************************************************************************
	> File Name: pipe.c
	> Author: Angel Criss
	> Mail: abbytsing@gmail.com 
	> Created Time: 一  3/31 17:26:55 2014
 ************************************************************************/

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
    if(argc<2)
    {
        printf("run by: ./a.out string\n");
        exit(0);
    }
    else
    {
        int len=0;
        pid_t pid;
        int fd[2]; //fd is unamed pipe

        while(argv[1][len])
        {
            len++; //get the para length
        }
        char *buf;
        buf=alloca(len);//make len size memery for argv[1]
        printf("argv[1] length is: %d\n",len);

        if(pipe(fd)==0)
            printf("\n\ncreated pipe\n\n"); //make unamed pipe
        else
        {
            perror("pipe");
            exit(0);
        }
        pid=fork();
        /*
         *   Data wirte to fildes[1] and read from fildes[0]
         */
        if(pid==0)
        {
            // read data from child process
            sleep(3);//make child process sleep wait parent process write data
            close(fd[1]);//close write
            if(read(fd[0],buf,len))
            {
                printf("the data write is: \n\n\t%s\n",buf);
            }
            else
            {
                perror("read");
                exit(0);
            }
        }
        else if(pid>0)
        {
            //write data from parent process
            close(fd[0]);//close read
            if(write(fd[1],argv[1],len)>0)
            {
                printf("\ndata wrote to pipe\n");
            }
            else
            {
                printf("write");
                exit(0);
            }
        }
    }
    exit(0);
}
